<script setup>
import {FileMapping, Role, User} from '@/utils/resource'
import util from '../../utils/util'
import {showSaveResponse, validateForm, validFieldExists} from '@/utils/element-helper'
import * as qiniu from 'qiniu-js'
import {reactive, ref} from "vue";
import {appStore} from "@/store/user";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {CircleCheck} from "@element-plus/icons-vue";

let maxsize = 1024 * 1024   // 最大1MB
let token

const loading = ref(false)
const form = ref(null)
const appS = appStore()
const router = useRouter()
const state = reactive({
  initForm: {},// for edit
  currentRole: {},
  form: {
    gender: "1",
  },
  img: {
    complete: false,
    total: {
      percent: 0
    },
    size: 0,
    url: ''
  },
  rules: {
    nick: [
      {required: true, message: '账号不能为空', trigger: 'blur'},
    ],
    email: [
      {required: true, message: '邮箱地址不能为空', trigger: 'blur'},
      {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']},
      {
        validator, trigger: 'blur'
      }
    ],
    phone: [
      {required: true, message: '手机号码不能为空', trigger: 'blur'},
      {pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码'},
      {
        validator, trigger: 'blur'
      }
    ],
    pass: [
      {min: 5, max: 25, message: '密码长度在 5 到 25 位之间', trigger: 'blur'},
    ],
  }
})


loadUser()
loadCurrentRole()

function loadUser() {
  let user = appS.user
  user.gender = String(user.gender)
  if (user.avatar === '' || user.avatar == null) {
    user.avatar = require('@/assets/SzauKZv.png')
  }
  state.img.url = user.avatar
  state.form = user
  state.initForm = user
}

async function loadCurrentRole() {
  let res = await Role.getCurrentRole()
  state.currentRole = res.data.data
}

function submitForm(formName) {
  return validateForm(form, formName, () => {
    //不修改密码需要将密码清空
    let tempForm = Object.assign({}, state.form)
    if (tempForm.pass === '') {
      delete tempForm['pass']
    }
    showSaveResponse(loading.value, () => User.modify(tempForm), () => {
          router.back()
        }
    )
  })
}

function validator(rule, value, callback) {
  validFieldExists(rule, value, callback, state.initForm[rule.field] !== value, (rule, value) => User.exists(rule, value))
}

//上传文件改变
async function change(e) {
  if (token) return upload(e.target)
  let res = await FileMapping.uploadToken()
  token = res.data.data
  upload(e.target)
}

function back() {
  router.back()
}

function upload(target) {
  if (target.files.length === 0) return
  let file = target.files[0]
  if (file.size > maxsize) {
    return ElMessage.error('文件大小超过限制, 请上传小于' + util.fileSize(maxsize) + '的图片')
  }
  Object.assign(state.img, {
    complete: false,
    total: {
      percent: 0,
      loaded: 0,
      size: 0
    },
    size: file.size,
    name: file.name,
    type: file.type,
    url: ''
  })
  let reader = new FileReader() // 如果为图片文件, 读取DataURL显示图片
  reader.readAsDataURL(file)
  reader.onload = (e) => state.img.url = e.target.result
  let key = util.shorten() + file.name.substr(file.name.lastIndexOf('.'))
  qiniu.upload(file, key, token).subscribe({ // 开始上传
    next: (res) => state.img.total = res.total,
    error: (err) => console.log('error', err),
    complete(res) {
      state.img.complete = true
      let item = {
        parent: 10,//头像文件夹编号
        name: state.img.name,
        mime: state.img.type,
        size: state.img.size,
        hash: state.img.hash,
        key: res.key,
        folder: 0,
      }
      FileMapping.save(item, "post").then(response => {
        Object.assign(state.img, response.data.data)
        let avatar = response.data.data.url
        User.avatar({avatar}).then(res => {
          if (res.data.code ===0) {
            ElMessage.success('头像已更新')
          }
        })
      })
    }
  })
  target.value = ''
}

</script>

<template>
  <div>
    <div style="height: 50px;">
      <p style="font-weight: normal;font-size: 24px;">个人资料</p>
    </div>
    <el-row style="background-color: white;padding: 15px;">
      <el-col :span="6">
        <div style="padding: 25px">
          <div class="card img-hover">
            <label class="img-mask">
              <i class="el-icon-picture" style="padding: 10px"></i> 点击上传头像
              <input type="file" accept="image/*" hidden @change="change">
            </label>
            <!--上传照片-->
            <img :src="state.img.url" class="avator-img">
          </div>
        </div>
        <div>
          <div style="float: left;width: 100%;padding: 15px 0px 15px 30px;">
            <span style="color: #303133;">{{ state.form.name }}</span>
            <span style="color: #606266;font-size: 15px;margin-left: 10px">{{ state.currentRole.name }}</span>
          </div>
          <div class="clearfix"></div>
          <div style="padding: 15px 0px 0px 30px;color: #909399">最近登录时间：</div>
          <div style="padding: 15px 0px 0px 30px;color: #909399">{{ state.form.visited }}</div>
        </div>
      </el-col>
      <el-col :span="18" style="padding: 15px">
        <el-form :model="state.form" label-position="top" :rules="state.rules" ref="form" label-width="100px" class="user-form">
          <el-form-item label="昵称" prop="nick" class="my-form-item">
            <el-input v-model="state.form.nick"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass" class="my-form-item">
            <el-input v-model="state.form.pass" type="password" placeholder="密码（无需修改请留空）"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="my-form-item">
            <el-input v-model="state.form.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" class="my-form-item">
            <el-input v-model="state.form.phone"></el-input>
          </el-form-item>
          <el-form-item label="生日" prop="birthday" class="my-form-item">
            <el-date-picker type="date" placeholder="选择生日" v-model="state.form.birthday"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item label="性别" prop="gender" class="my-form-item">
            <el-radio-group v-model="state.form.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        &nbsp;
      </el-col>
      <el-col :span="18">
        <div style="padding: 15px">
          <el-button plain round type="info" @click="back" icon="Back">返回</el-button>
          <el-button plain type="primary" @click="submitForm('form')" icon="CircleCheck">保存</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>


<!-- Add "scoped" attribute to limit CSS to state component only -->
<style scoped>
.user-form {
  width: 90%;
}

.my-form-item {
  max-width: 600px;
}

.my-form-input {
  max-width: 330px;
}

.img-mask:hover {
  background: rgba(0, 0, 0, .6);
  cursor: pointer;
}

.img-mask:hover,
.img-hover:hover .img-mask {
  opacity: 1;
  visibility: visible;
}

.avator-img {
  max-width: 100%;
  height: auto;
  border-radius: .25rem .25rem 0 0;
  display: block;
}

.img-mask {
  color: #fff !important;
  border-radius: .25rem .25rem 0 0;
  background: rgba(0, 0, 0, .3);
  width: 100%;
  height: 15%;
  min-height: 35px;
  margin: 0;
  opacity: 0;
  visibility: hidden;
  text-align: center;
  position: absolute;
  transition: all .3s ease-in-out;
}

.card {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border: 1px solid rgba(0, 0, 0, .125);
  border-radius: .25rem;
}
</style>
